package com.niit.user.service.impl;


import cn.hutool.json.JSONUtil;
import com.niit.user.entity.User;
import com.niit.user.service.MessageService;
import com.niit.user.service.MySource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Processor;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.MessageBuilder;

/**
 * @author yaojianfeng
 * @EnableBinding 定义消息的推送管道, 开启绑定功能
 * 异步消息发送实现类
 */
@EnableBinding({Sink.class, Source.class, MySource.class})
public class MessageServiceImpl implements MessageService {
    @Autowired
    @Qualifier("output")
    private MessageChannel channel;
    @Autowired
    @Qualifier("output1")
    private MessageChannel channel1;
    @Autowired
    @Qualifier("output2")
    private MessageChannel channel2;

    @Override
    public String send(String channelName, String msg) {
        Message<String> build = MessageBuilder.withPayload(msg).build();
        boolean sendFlag;
        switch (channelName) {
            case MySource.OUTPUT1:
                sendFlag = channel1.send(build);
                break;
            case MySource.OUTPUT2:
                sendFlag = channel2.send(build);
                break;
            default:
                sendFlag = channel.send(build);
                break;
        }
        if (sendFlag) {
            return "The message was sent successfully: " + msg;
        }
        return "Failed to send the message: " + msg;
    }

    /**
     * 发送消息方法
     * @param channelName 管道名称
     * @param user 待发送的对象
     * @return 发送结果
     */
    @Override
    public String send(String channelName, User user) {
        // 序列化对象为json字符串
        String msg = JSONUtil.toJsonStr(user);
        return send(channelName, msg);
    }

    /**
     * 接收到消息的处理方法 这里只是打印一下接收到的消息
     * @param msg 接收到的回执消息
     */
    @StreamListener(Sink.INPUT)
    public void receiveReturnMessage(Message<String> msg) {
        System.out.println("receiveReturnMessage : " + msg.getPayload());
    }
}
